package cuit.blog.controller;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cuit.blog.entity.Article;
import cuit.blog.entity.Articletype;
import cuit.blog.entity.Reply;
import cuit.blog.entity.User;
import cuit.blog.service.ArticleService;
import cuit.blog.service.ArticletypeService;
import cuit.blog.service.ReplyService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;


@Controller
@RequestMapping("/reply")
public class ReplyController {
	@Autowired
	ReplyService replyService;
	@Autowired
	ArticleService articleService;
	int pageSize = 10;
	
	
	@PostMapping("/save")
	public String saveReply(HttpServletRequest request,@RequestParam("articleId") Long articleId, @ModelAttribute("reply") Reply reply) {
		User user;
		HttpSession session = request.getSession();
		Article article = articleService.findById(articleId);
		if (session.getAttribute("LoginUser") != null) {
			user = (User) session.getAttribute("LoginUser");
		} else {
			user = new User();
			user.setId(1);
		}
	    reply.setUser(user);
	    reply.setArticle(article);
	    
	    // 保存 reply 对象到数据库
	    replyService.save(reply);
	    
	    return "redirect:/article/show" + "?id=" +articleId; // 重定向到文章详情页
	}
	
	@GetMapping("/page")
	public String findByPage(HttpServletRequest request,@RequestParam("pageIndex") int pageIndex, Model model) {
		HttpSession session = request.getSession();
		User user= (User) session.getAttribute("LoginUser");
		Page<Reply> Page = replyService.getRepliesByUser(user.getId(),pageIndex, pageSize);
		model.addAttribute("replyPage", Page);
		return "reply/list";
	}
	@GetMapping("/rpage")
	public String findByPageForRoot(@RequestParam("pageIndex") int pageIndex, Model model) {
		Page<Reply> Page = replyService.findAllByPage(pageIndex, pageSize);
		model.addAttribute("replyPage", Page);
		return "root/replylist";
	}
	@GetMapping(path = "/delete")
	public String delete(@RequestParam long id,HttpServletRequest request) {
		replyService.deleteById(id);
		User user;
		HttpSession session = request.getSession();
		if (session.getAttribute("LoginUser") != null) {
			user = (User) session.getAttribute("LoginUser");
			if(user.getUsername().equals("root")) {
				return "redirect:/reply/rpage?pageIndex=0";
			}
		}
		return "redirect:/reply/page?pageIndex=0";
	}
}